"use client";

import React, { useEffect, useState } from "react";
import { Form, Input, Button, Space, message, Descriptions } from "antd";
import { getRecruitmentAnnouncements, updateRecruitmentAnnouncement, PlanType } from "@/lib/recruitment";

// 辅助函数，根据枚举值返回对应的显示文本
const getPlanTypeText = (type: number): string => {
	switch (type) {
		case PlanType.MANAGEMENT:
			return "管理岗位";
		case PlanType.TEACHER:
			return "专任教师";
		case PlanType.OTHER:
			return "其他岗位";
		default:
			return "未知类型";
	}
};

interface EditPlanFormProps {
	onSuccess: () => void;
	onCancel: () => void;
	planId?: string; // 添加可选的planId属性
}

const EditPlanForm: React.FC<EditPlanFormProps> = ({ onSuccess, onCancel, planId: propPlanId }) => {
	const [form] = Form.useForm();
	const [loading, setLoading] = useState(false);
	const [planType, setPlanType] = useState<number>(1);
	const [announcement, setAnnouncement] = useState<any>({});

	// 加载招聘公告数据，不回显时间、附件、审批人、部门和岗位相关信息，仅显示其它字段
	useEffect(() => {
		const params = new URLSearchParams(window.location.search);
		// 优先使用props传入的planId，如果没有则使用URL参数
		const planId = propPlanId || params.get("planId");
		if (planId) {
			getRecruitmentAnnouncements()
				.then((res: any) => {
					if (res.code === 1) {
						const data = res.data.find((item: any) => Number(item.planId) === Number(planId));
						if (data) {
							console.log("获取到的招聘计划数据:", data);
							setAnnouncement(data);
							setPlanType(data.planType);
							if (data.planType === PlanType.OTHER) {
								// 仅当为其他岗位时，公告内容可以编辑
								form.setFieldsValue({
									content: data.content || "",
								});
							}
						} else {
							message.error("未找到对应的招聘公告数据");
						}
					} else {
						message.error("获取招聘公告数据失败");
					}
				})
				.catch((error: any) => {
					console.error("加载招聘公告数据失败：", error);
					message.error("加载招聘公告数据失败");
				});
		} else {
			message.error("缺少 planId 参数");
		}
	}, [form, propPlanId]);

	// 当 planType === PlanType.OTHER 时，仅提交公告内容更新
	const handleSubmit = async (values: any) => {
		setLoading(true);
		try {
			const updateData: any = { planId: announcement.planId };
			if (planType === PlanType.OTHER) {
				if (!values.content) {
					message.error("公告内容不能为空");
					setLoading(false);
					return;
				}
				updateData.content = values.content;
			}
			console.log("提交数据：", updateData);
			await updateRecruitmentAnnouncement(updateData);
			message.success("操作成功");
			onSuccess();
		} catch (error: any) {
			message.error(error.message || "操作失败");
		} finally {
			setLoading(false);
		}
	};

	return (
		<div style={{ padding: 24 }}>
			{/* 输出完整数据内容，方便调试 */}
			<div style={{ display: 'none' }}>
				<pre>{JSON.stringify(announcement, null, 2)}</pre>
			</div>
			
			{/* 回显基本信息（时间、附件、审批人、部门和岗位信息不显示），并移除"审批状态" */}
			<Descriptions title="招聘公告基本信息" bordered column={1} style={{ marginBottom: 24 }}>
				<Descriptions.Item label="计划ID">{announcement.planId}</Descriptions.Item>
				<Descriptions.Item label="名称">{announcement.planName}</Descriptions.Item>
				<Descriptions.Item label="编号">{announcement.planCode}</Descriptions.Item>
				<Descriptions.Item label="招聘类型">{getPlanTypeText(announcement.planType)}</Descriptions.Item>
				<Descriptions.Item label="招聘负责人工号">{announcement.recruiterId}</Descriptions.Item>
				<Descriptions.Item label="招聘负责人">{announcement.recruiterName}</Descriptions.Item>
				<Descriptions.Item label="联系电话">{announcement.recruiterPhone}</Descriptions.Item>
				<Descriptions.Item label="招聘条件">{announcement.recruitmentConditions}</Descriptions.Item>
				<Descriptions.Item label="待遇说明">{announcement.benefitsDescription}</Descriptions.Item>
				<Descriptions.Item label="面试流程">{announcement.interviewProcess}</Descriptions.Item>
				<Descriptions.Item label="备注">{announcement.notes}</Descriptions.Item>
				{planType === PlanType.OTHER && (
					<Descriptions.Item label="公告内容">{announcement.content}</Descriptions.Item>
				)}
			</Descriptions>

			{/* 当计划类型为其他岗位时，允许修改公告内容 */}
			{planType === PlanType.OTHER ? (
				<Form form={form} layout="vertical" onFinish={handleSubmit}>
					<Form.Item
						name="content"
						label="公告内容"
						rules={[{ required: true, message: "请输入公告内容" }]}
					>
						<Input.TextArea rows={4} placeholder="请输入公告内容" />
					</Form.Item>
					<Space style={{ marginTop: 16 }}>
						<Button onClick={onCancel}>取消</Button>
						<Button type="primary" htmlType="submit" loading={loading}>
							提交
						</Button>
					</Space>
				</Form>
			) : (
				<Space style={{ marginTop: 16 }}>
					<Button onClick={onCancel}>关闭</Button>
				</Space>
			)}
		</div>
	);
};

export default function Page({ planId }: { planId?: string } = {}) {
	const handleCancel = () => {
		// 使用window.parent查找父窗口中的Modal并关闭
		const modal = window.parent.document.querySelector('.ant-modal-close');
		if (modal) {
			(modal as HTMLElement).click();
		}
	};

	return (
		<EditPlanForm
			onCancel={handleCancel}
			onSuccess={handleCancel}
			planId={planId}
		/>
	);
}